package com.simple.relaxed.utils;

import com.google.gson.Gson;
import com.simple.relaxed.anno.Mark;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Mark(methodName = "getInstance")
public class HttpUtil {

    private OkHttpClient okHttpClient;

    private static HttpUtil httpUtil = new HttpUtil();

    private HttpUtil() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.DAYS)
                .readTimeout(1, TimeUnit.DAYS)
                .callTimeout(1, TimeUnit.DAYS)
                .writeTimeout(1, TimeUnit.DAYS)
                .build();
    }

    public static HttpUtil getInstance() {
        if (httpUtil == null) {
            httpUtil = new HttpUtil();
        }
        return httpUtil;
    }

    /**
     * 调用此方法，执行阻塞型get申请
     *
     * @param url    资源地址
     * @param params 申请参数map集合
     * @return 返回值对象
     */
    public Response syncGetApply(String url, Map<String, Object> params) {
        HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                builder.addQueryParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(builder.build());
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 调用此方法，执行非阻塞任务
     *
     * @param url      资源第hi
     * @param params   申请参数map集合
     * @param callback 成功或者失败时，被回调的对象
     */
    public void asyncGetApply(String url, Map<String, Object> params, Callback callback) {
        HttpUrl.Builder newBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                newBuilder.addQueryParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(newBuilder.build());
        Request request = requestBuilder.build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 使用此方法执行异步post请求
     *
     * @param url      请求资源
     * @param params   请求参数
     * @param callback 请求成功或者失败时，回调的对象
     */
    public void asyncPostApply(String url, Map<String, Objects> params, Callback callback) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Gson gson = new Gson();
        String toJson = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(JSON, toJson);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .post(requestBody);
        Request request = builder.build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 使用此方法，实现同步post请求
     *
     * @param url    请求资源
     * @param params 请求参数
     * @return 请求对象
     */
    public Response syncPostApply(String url, Map<String, Objects> params) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Gson gson = new Gson();
        String toJson = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(JSON, toJson);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url)
                .post(requestBody)
                .build();
        try {
            return okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
